#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

#define SIZE 81
#define LIMIT 20
#define swap(type, a, b)    do {type c=a; a=b; b=c;} while(0)


char * s_gets(char *, int);
char * str_char_search(const char *, char);
char getchar2(void);

int main(void)
{
    char str[SIZE] ;
    char ch;
    char * find;

    printf("test strchr my implements.\n");
    printf("enter empty line to quit!\n");

    printf("enter string:\n");
    while ( (s_gets(str, SIZE)) != NULL && *str != '\0') {
        printf("enter char will be find:\n");
        ch = getchar2();

        find = str_char_search(str, ch);

        printf("string is \"%s\"(pt:%p).\n", str, str);

        if (find == NULL)
            printf("Not found '%c'.\n", ch);
        else
            printf("a pointer is %p of '%c', postion is %ld.\n",find, ch, find - str);

        printf("enter string:\n");
    }

    puts("Bye!\n");

    return 0;
}

char * str_char_search(const char * str, char ch)
{
    /* if (!str) return (char *)str; let client examine */
    while (*str && *str != ch)
        ++str;

    return *str ? (char *)str : NULL;
}

char getchar2()
{
    char ch;
    while (isspace(ch = getchar()))
        ;

    while (getchar() != '\n')
        ;
    return ch;
}

char * s_gets(char * str, int n)
{
    char * ret_val;

    ret_val = fgets(str, n, stdin);

    if (ret_val) {
        while (*str != '\n' && *str != '\0')
            ++str;
        if (*str == '\n')
            *str = '\0';
        else
            while (getchar() != '\n')
                ;
    }

    return ret_val;
}
